﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class SendSingleSMS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadLogin();
            loadGroup();
        }
    }


    private void loadLogin()
    {
        if (hfLoginID.Value == "")
        {
            hfLoginID.Value = getLogin().ToString();
        }
    }

    private string getLoginID()
    {
        return hfLoginID.Value.Substring(6, hfLoginID.Value.Length - 6).Substring(0, hfLoginID.Value.Length - 12);


    }
    private string getLogin()
    {
        string loginID = "";
        try
        {
            if (Session["OnlineSMS_LoginID"] != null)
            {
                loginID = Session["OnlineSMS_LoginID"].ToString();
            }
            else if (hfLoginID.Value != "")
            {
                loginID = hfLoginID.Value;
            }
            else
            {
                Session["PreviousPage"] = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect("Default.aspx");
            }

        }
        catch (Exception ex)
        { }

        return loginID;
    }

    private void loadGroup()
    {
        string sql = @"
SELECT  [GroupID]
      ,[GroupName]
      ,[dbo].[GetContactCountyLoginID](GroupID) as NoOfContacts
  FROM [Group] where StatusID=1 and LoginID=" + getLoginID() + @"
order by GroupName
";

        DataSet ds = DatabaseManager.ExecSQL(sql);

        chklGroup.Items.Clear();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            chklGroup.Items.Add(new ListItem(dr["GroupName"].ToString() + "(" + decimal.Parse(dr["NoOfContacts"].ToString()).ToString() + ")", dr["GroupID"].ToString()));
        }

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (txtMasking.Text.Trim() == "")
            return;

       

        if (txtSMS.Text.Trim() == "")
            return;

        if (balanceChecking())
        {
            lblReport.Text = "You balance is not sufficient to send SMS";
            return;
        }
        
        int totalSend = 0;
        int totalNotSend = 0;
        int noOfSMS = SendSMS.countSMS(txtSMS.Text.Trim());
        string ids = "";
        try
        {
            string sql = "select ContactID, MobileNo from Contact where GroupID=5";
            DataSet ds = DatabaseManager.ExecSQL(sql);
            
            foreach (DataRow  nos in ds.Tables[0].Rows)
            {
                string no = nos["MobileNo"].ToString();
                if (no.Trim() != "")
                {
                    if (SendSMS.sendSMS(getLoginID(), txtMasking.Text.Trim(), no, txtSMS.Text))
                    {
                        totalSend++;
                    }
                    else
                    {
                        totalNotSend++;
                        ids += "," + nos["ContactID"].ToString();
                    }
                }
            }

            
            sql= @"
                        INSERT INTO [SMS]
                                   ([SMS]
                                   ,[LoginID]
                                   ,[SendDate]
                                   ,[Size]
                                   ,[LetterCount]
                        ,[Masking]
                                   ,[SendTo])
                             VALUES
                                   (N'" + txtSMS.Text.Replace("'","''")+@"'--<SMS, nvarchar(max),>
                                   ,"+getLoginID()+ @"--<LoginID, bigint,>
                                   ,GETDATE()--<SendDate, datetime,>
                                   ,"+noOfSMS.ToString()+@"--<Size, int,>
                                   ," + txtSMS.Text.Trim().Length.ToString() + @"--<LetterCount, int,>
                                   ,'" + txtMasking.Text + @"'--<SendTo, nvarchar(max),>
                                   ,'" + ids + @"'--<SendTo, nvarchar(max),>
                        );
                        ";
            DatabaseManager.ExecSQL(sql);
        }
        catch (Exception ex)
        {
            lblReport.Text = "Error Occured !!! <br/>";
        }
            lblReport.Text = "Total SMS sent :" + totalSend + " X " + noOfSMS + " = " + (totalSend*noOfSMS).ToString();
            if(totalNotSend!=0)
                lblReport.Text += "<br/><span style='color:red;'>Total Not sending SMS:" + totalSend + " X " + noOfSMS + " = " + (totalSend * noOfSMS).ToString()+"</span>";

    }

    private bool balanceChecking()
    {
        int smsNeedTosend = 0;
        foreach (ListItem item in chklGroup.Items)
        {
            if (item.Selected)
            {
               smsNeedTosend+= int.Parse(item.Text.Split('(')[1].Split(')')[0].Trim().Replace(",", ""));
            }
        }

        if (SendSMS.remainingSMS(getLoginID()) >= smsNeedTosend) return true;
            else 
        return false;
    }
}